import Store from '@/store'
import Utils from '@/utils/utils'

// 校验手机号是否合法
export const checkPhone = phone => {
	// 匹配以 1 开头，第二位为 3-9 的数字，后面跟着 9 个数字的正则
	let reg = /^1[3-9]\d{9}$/g
	
	// true：合法，false：不合法
	return reg.test(phone)
}

// 根据系统时间获取问候语
export const getToGreet = () => {
	let now = new Date()
	let hours = now.getHours()
	let greet = ''
	
	if (hours >= 0 && hours < 10) {
		greet = '早上好'
	} else if (hours >= 10 && hours <= 11) {
		greet = '上午好'
	} else if (hours > 11 && hours <= 13) {
		greet = '中午好'
	} else if (hours > 13 && hours <= 18) {
		greet = '下午好'
	} else if (hours > 18 && hours < 24) {
		greet = '晚上好'
	}
	
	return greet
}

// 获取当前系统时间(年月日)
export const getCurrentDate = () => {
	let now = new Date()
	let year = now.getFullYear()
	let month = now.getMonth() + 1
	let day = now.getDate()
	
	return year + '年' + month + '月' + day + '号'
}

// 获取当前系统年份
export const getCurrentYears = () => {
	let now = new Date()
	let year = now.getFullYear()
	
	return year
}

// 获取当前日期（周几）
export const getCurrentWeek = () => {
	let now = new Date()
	let week = now.getDay() === 0 ? 7 : now.getDay()
	let currentWeek = ''
	
	switch (week) {
		case 1:
			currentWeek = '星期一'
			break;
		case 2:
			currentWeek = '星期二'
			break;
		case 3:
			currentWeek = '星期三'
			break;
		case 4:
			currentWeek = '星期四'
			break;
		case 5:
			currentWeek = '星期五'
			break;
		case 6:
			currentWeek = '星期六'
			break;
		case 7:
			currentWeek = '星期日'
			break;
	}
	
	return currentWeek
}

// 获取当前系统日期：年月日 时分秒
// timestamp：时间戳
export const getSystemDate = (timestamp, format) => {
	let now = timestamp ? new Date(timestamp) : new Date()
	let year = now.getFullYear()
	let month = now.getMonth() + 1
	let day = now.getDate()
	let hour = now.getHours()
	let minute = now.getMinutes()
	let second = now.getSeconds()
	let dates = ''
	
	month = month > 9 ? month : '0' + month
	day = day > 9 ? day : '0' + day
	hour = hour > 9 ? hour : '0' + hour
	minute = minute > 9 ? minute : '0' + minute
	second = second > 9 ? second : '0' + second
	
	
	// format 输出格式：
	// yyyy-MM-dd HH:mm:ss
	// yyyy/MM/dd HH:mm:ss
	// yyyy-MM-dd HH:mm
	// yyyy/MM/dd HH:mm
	// yyyy-MM-dd
	// yyyy/MM/dd
	// HH:mm:ss
	
	if (format) {
		// 如果要求了格式
		if (format === 'yyyy-MM-dd HH:mm:ss') {
			dates = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
		} else if (format === 'yyyy/MM/dd HH:mm:ss') {
			dates = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second
		} else if (format === 'yyyy-MM-dd HH:mm') {
			dates = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
		} else if (format === 'yyyy/MM/dd HH:mm') {
			dates = year + '/' + month + '/' + day + ' ' + hour + ':' + minute
		} else if (format === 'yyyy/MM/dd') {
			dates = year + '/' + month + '/' + day
		} else if (format === 'yyyy-MM-dd') {
			dates = year + '-' + month + '-' + day
		} else if (format === 'HH:mm:ss') {
			dates = hour + ':' + minute + ':' + second
		} else {
			dates = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second
		}
	} else {
		// 没有要求输出格式，那么将以 yyyy/MM/dd HH:mm:ss 格式输出
		dates = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second
	}
	
	return dates
}

// 获取应用缓存大小
export const getPlusCacheSize = () => {
	let info = uni.getStorageInfoSync()
	let currentSize = info.currentSize
	let size = ''
	
	if (currentSize >= 1024) {
		size = Math.round(((currentSize / 1024) * 100)) / 100 + 'MB'
	} else {
		size = currentSize + 'KB'
	}
	
	return size
}

// 验证是否登录
export const checkLogin = () => {
	let isLogin = Store.state.user.isLogin
	let token = Store.state.user.token
	let noAuthUrls = Store.state.user.noAuthUrls
	let mobile = Store.state.user.mobile
	
	// 获取当前页面
	let pages = getCurrentPages()
	let route = pages[pages.length - 1].route
	
	if (!isLogin || !token) {
		if (noAuthUrls.indexOf(route) !== -1) {
			if (route === 'pages/captch/captch' && !mobile) {
				Utils.popUpMsg('error', '请登录！', 500)
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}, 500)
			}
		} else {
			Utils.popUpMsg('error', '请登录！', 500)
			
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}, 500)
		}
	} else {
		if (noAuthUrls.indexOf(route) !== -1) {
			Utils.popUpMsg('error', '您已登录！', 500)
			
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}, 500)
		}
	}
}

// 获取坐标（此方法为 uniapp 官方提供）
// type：默认为 gcj02 返回 gps 坐标
// isHighAccuracy：是否开启高精度
// highAccuracyExpireTime：高精度超时时间，设置 3000ms 以上才有效
export const getUserLocation = (type, isHighAccuracy, highAccuracyExpireTime) => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
		    type: type ? type : 'wgs84',
		    isHighAccuracy: isHighAccuracy ? isHighAccuracy : true,
			highAccuracyExpireTime: highAccuracyExpireTime ? highAccuracyExpireTime : 10000,
		    success: (res) => {
				// Utils.popUpMsg('none', `坐标获取成功，经度：${res.longitude}、纬度：${res.latitude}`, 5000)
				resolve(res)
		    },
			fail: (err) => {
				// Utils.popUpMsg('none', `坐标获取失败：${err}`, 5000)
				reject(err)
			}
		})
	})
}

// 将文件流转为 base64
export const fileToBase64 = (file) => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader()
		
		reader.onloadend = () => {
			const base64String = reader.result.split(',')[1]
			// callback(base64String)
			resolve(base64String)
		}
		
		reader.readAsDataURL(file)
	})
}

// 从字符串中某个字符出现的最后一个位置开始截取
// str：要截取的字符
// data：被截取的字符串
export const getSubstring = (data, str) => {
	let lastIndex = data.lastIndexOf(str)
	let newStr = lastIndex !== -1 ? data.substring(lastIndex + 1) : data
	
	return newStr
}

// 将后台返回的图片资源地址前缀修改一下
// 将 HMP_003 改为 img
export const getStaticUrl = (url) => {
	let newUrl = 'img' + url.substring(7, url.length)
	
	return newUrl
}

// 将字符串中字母小写转为大写
export const convertLetterCase = (val) => {
	let str = val
	
	if (val && typeof val === 'string') {
		str = val.toUpperCase()
	}
	
	return str
}